package io.github.jsp.executor;

import io.github.jsp.model.JobInfo;
import io.github.jsp.model.JobLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class PrintJobHandler implements JobHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(PrintJobHandler.class);
    
    @Override
    public void execute(JobInfo jobInfo, JobLog jobLog) throws Exception {
        String message = "Default message";
        
        if (jobInfo.getJobParam() != null && jobInfo.getJobParam().contains("message")) {
            message = extractMessageFromParam(jobInfo.getJobParam());
        }
        
        logger.info("PrintJob executing: {}", message);
        System.out.println("PrintJob Output: " + message + " at " + new java.util.Date());
    }
    
    private String extractMessageFromParam(String param) {
        try {
            if (param.contains("\"message\"")) {
                int start = param.indexOf("\"message\"") + "\"message\"".length();
                start = param.indexOf("\"", start) + 1;
                int end = param.indexOf("\"", start);
                if (end > start) {
                    return param.substring(start, end);
                }
            }
        } catch (Exception e) {
            // ignore
        }
        return "Default message";
    }
}